package com.emm.yixun.mobile.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.Login;
import com.eroad.product.tools.PopuContent;
import com.eroad.product.tools.Result;
import com.example.xf.MainActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;
import xf.tools.Loading;

import static android.Manifest.permission.VIBRATE;

/**
 * <p>
 * <b>Title：</b> 登陆界面
 * </p>
 * <p>
 * <b>Description：</b> 未登录、重新登录 进入该界面
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午3:54:47
 */
public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";

    /**
     * 手机号或账号输入框
     */
    EditText ed_code;

    /**
     * 密码输入框
     */
    EditText ed_pwd;

    /**
     * 登陆按钮
     */
    Button btn_y;

    private String isonresume = "0";

    TextView version_name;

    @Override
    protected void onResume() {
        BaseActivity.activity = this;
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        BaseActivity.activity = this;
        Log.v(TAG, "EmmApplication.count:" + EmmApplication.count);

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

        isonresume = getIntent().getStringExtra("isonresume");

        if (null == isonresume || "".equals(isonresume) || "null".equals(isonresume)) {
            isonresume = "0";
        }

        initView();
        initBtn();

        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(VIBRATE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            show();
                        } else {
                            show();
                        }
                    }
                });
    }

    private void show() {
        PopuContent.show(LoginActivity.this, "您已拒绝app的显示通知权限申请，将导致您无法得到信息提示", -1, new Result() {
            @Override
            public void result() {
            }
        });
    }

    private void initView() {
        ed_code = (EditText) findViewById(R.id.ed_code);
        ed_pwd = (EditText) findViewById(R.id.ed_pwd);
        btn_y = (Button) findViewById(R.id.btn_y);
        version_name = (TextView) findViewById(R.id.version_name);
        version_name.setText(" v" + EmmApplication.getPackageManager(9));
    }

    private void initBtn() {
        String str = EmmApplication.getData(EmmApplication.Project_LoginCode);
        if (null != str) {
            ed_code.setText(str);
        }

        btn_y.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(ed_code.getText().toString())) {
                    EmmApplication.T("用户名不能为空");
                } else {
                    if ("".equals(ed_pwd.getText().toString())) {
                        EmmApplication.T("密码不能为空");
                    } else if (ed_pwd.getText().toString().length() < 6) {
                        EmmApplication.T("密码至少6位");
                    } else if (ed_pwd.getText().toString().length() > 20) {
                        EmmApplication.T("密码最多20位");
                    } else {
                        // 本地校验完成，可以实行登陆操作
                        LoginPost();
                    }
                }
            }
        });
    }

    /**
     * 登陆接口
     */
    private void LoginPost() {
        EmmApplication.updateUrl("login");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        // map.put("merchantCode", EmmApplication.merchantCode);
        map.put("loginName", ed_code.getText().toString().trim());
        map.put("loginPwd", ed_pwd.getText().toString());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("deviceToken", JPushInterface.getRegistrationID(this));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.w("login___>post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(LoginActivity.this, "登录中...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    Log.v(TAG, "数据为空");
                    return;
                }
                Log.v("登陆请求成功", "userId : " + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "登陆信息返回值为空");
                    return;
                }
                Login login = JSONObject.parseObject(resData.toString(), Login.class);
                if ("1".equals(login.getResult())) {
                    String userId = login.getUserId();
                    Log.v("登入成功", "userId : " + userId);
                    EmmApplication.setIsLogin("1");// 存储是否已登录标识

                    EmmApplication.setIsLoginToken(login.getToken());// 存储token

                    EmmApplication.setIsLoginUserId(userId);// 存储userid

                    EmmApplication.setData(EmmApplication.merchantId, login.getMerchantId());// 存储merchantId

                    EmmApplication.setUserName(login.getUserName());// 存会员名

                    EmmApplication.setData(EmmApplication.ISPHONEINFORMATION, login.getIsPhoneInformation());// 是否已开通电话平台
                    // String(1)
                    // 是否已开通电话平台：0、未开通；
                    // 2、已开通

                    EmmApplication.setData(EmmApplication.FROMDETAILSTYPE, login.getIsPaydeposit());// 认筹
                    // (是否拥有权限
                    // 0、未开通；1、已开通)

                    try {
                        EmmApplication.setData(EmmApplication.FistSrcPatch, login.getLoginHandImgList().get(0)
                                .getHandLogoImg());
                    } catch (NullPointerException e) {
                    }

                    String str;
                    if ("1".equals(login.getRoleType())) {
                        str = "0";
                    } else {
                        str = "1";
                    }

                    // 存储模块权限↓
                    SetDateOrType(login.getIsHomePage(), EmmApplication.isHomePage);
                    SetDateOrType(login.getIsCustomer(), EmmApplication.isCustomer);
                    SetDateOrType(login.getIsHouses(), EmmApplication.isHouses);
                    SetDateOrType(login.getIsAnalysis(), EmmApplication.isAnalysis);
                    SetDateOrType(login.getIsMine(), EmmApplication.isMine);
                    SetDateOrType(login.getIsAddCustomer(), EmmApplication.isAddCustomer);
                    SetDateOrType(login.getIsDistributionCustomer(), EmmApplication.isDistributionCustomer);
                    SetDateOrType(login.getIsGradesMine(), EmmApplication.isGradesMine);
                    SetDateOrType(login.getIsHeroListMine(), EmmApplication.isHeroListMine);
                    SetDateOrType(login.getIsTeamRankingMine(), EmmApplication.isTeamRankingMine);

                    SetDateOrType(login.getIsAddPaydeposit(), EmmApplication.isAddPaydeposit);
                    SetDateOrType(login.getIsAddSigned(), EmmApplication.isAddSigned);
                    SetDateOrType(login.getIsAddSubscribe(), EmmApplication.isAddSubscribe);
                    EmmApplication.setData(EmmApplication.Project_LoginCode, ed_code.getText().toString().trim());

                    EmmApplication.setTips("");

                    // 执行登陆成功操作
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();

                } else {
                    EmmApplication.T("" + login.getErrorMsg().toString());
                    Log.v("登入失败", "errorCode:" + login.getErrorCode().toString() + "errorMsg:"
                            + login.getErrorMsg().toString());
                }
            }
        });
    }

    private void SetDateOrType(String str1, String name) {
        if ("".equals(str1) || "null".equals(str1) || "0".equals(str1)) {
            EmmApplication.setData(name, "0");
        } else {
            EmmApplication.setData(name, str1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "EmmApplication.count" + EmmApplication.count);
        EmmApplication.count = 0;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ("1".equals(isonresume)) {
                HOME(LoginActivity.this);
                Log.v("处于重新登录", "需要回到桌面");
                return false;
            }
        } else {
        }
        return super.onKeyDown(keyCode, event);
    }

    public void HOME(Context context) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(intent);
    }

}
